<?php
namespace app\webqun\controller;
use Exception;
use RuntimeException;
use think\Session;
use wechat\MchApi;
use wechat\Wechat;
use think\db\Expression;

/**
 *  @file : IndexController.php
 *  @brief: 后台操作基础类
 */
class IndexController extends BaseController {

  protected $beforeActionList = [
    'checkWxAuth' => [],  // 对于当前控制器来说, 里面的所有Action都需要选微信授权
    'checkHtAuth' => [  // 特殊Action不需要后台先登录
      'except' => 'login,register',
    ],
  ];
  /**
   *  @brief  : 微信公众号菜单-代理申请/代理登陆
   *  @return : page
   *  @details: http://gg.ag.game654.com/index/index.html
   */
  public function indexAction() {

    $Agent    = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    $RoomCard = table('UserRoomCard', 'rydb.treasure')->where(['UserID'=>$Agent['UserID'], 'KindID'=>0])->value('RoomCard');
    //////////////////////////////
    $Menu1 = []; // 私有菜单
    $eax = explode('|', str_replace('||', '|', trim($Agent['MenuStr'], '|'))); // 兼容.net版本
    $eax = empty($eax) ? [] : $eax;
    if (!empty($eax)) {
      $WX_AGENT_MENUS = config('WX_AGENT_MENUS');
      foreach($eax as $k) {
        if (array_key_exists($k, $WX_AGENT_MENUS)) {
          $Menu1[$k] = $WX_AGENT_MENUS[$k];
        }
      }
    }
    //////////////////////////////
    $Menu2 = [  // 公有菜单
      'exit'  => ['icon-2', '安全退出'],
    ];
    
    ////////////// 充值(30天) /////////////
    $p30 = 0;
    
    // 代理号自己充值30天总和
    $p30 = table('ChargeOnline', 'rydb.websms')->where(['UserID'=>$this->auid, 'Status'=>1, 'GameStatus'=>1, ['EXP', new Expression('DATEDIFF(DAY, Updatetime, GETDATE()) <= 30')]])->sum('RMB');
    /*
    // 代理号所关联群群主充值30天总和
    $AssoFamily = $Agent['AssoFamily'];
    $AssoFamily = empty($AssoFamily) ? [] : explode(',', $AssoFamily);
    if (!empty($AssoFamily)) {
      $BossID = table('Family', 'rydb.websms')->where(['Code' => ['IN', $AssoFamily]])->column('AUID');
      $BossID = array_keys($BossID);
      if(!empty($BossID)){
        $p30 = table('ChargeOnline', 'rydb.websms')->where([
          'Status' => 1, 'GameStatus' => 1, ['EXP', new Expression('DATEDIFF(DAY, Updatetime, GETDATE()) <= 30')],
          'UserID' => ['IN', $BossID],
        ])->sum('RMB');
      }
    }
    */
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'Agent' => $Agent,
      'Menu1' => $Menu1,
      'Menu2' => $Menu2,
      'RoomCard' => $RoomCard,
      'p30'   => $p30 * 1,
    ]);
  }
  /**
   *  @brief  : 登陆页面&&登陆
   *  @return : page|redirect|JSON
   *  @details:
   */
  public function loginAction() {
    $auid = Session::get('HTOAUTH.AUID');
    if ($auid > 0) { // 已经登陆过, 则直接重定向至首页或ref页面
      $ref = $this->request->param('ref/s', '');
      $url = empty($ref) ? url('index') : $ref;
      return $this->redirect($url);
    }
    if ($this->request->isGet()) {
      return $this->fetch('', []);
    }
    // 登陆表单处理
    //--- 验证器验证, 按照顺序逐一判断 ---
    $retn = $this->validate($_REQUEST, [
      'sjhm|手机号码' => 'require|mobile',
      'aqmm|安全密码' => 'require|regex:/^[\S]{1,16}$/',
    ]);
    if (true !== $retn) {
      return result([], 101, $retn);
    }
    //--- 数据库验证 ---
    $sjhm = $this->request->param('sjhm/s', '', 'trim');
    $aqmm = $this->request->param('aqmm/s', '', 'trim');

    $Agent = table('AgentReg', 'rydb.websms')->where(['Channel' => $this->Channel, 'MobilePhone' => $sjhm])->find();
    if (empty($Agent)) {
      return result([], 102, '账号不存在');
    }
    if ($Agent['Status'] != 1) {
      return result([], 103, '账号未审核通过');
    }
    if ($Agent['DisableLogin'] == 1) {
      return result([], 104, '您的帐号不存在');
    }
    if ($Agent['LogonPass'] != $aqmm) {
      return result([], 105, '密码不正确');
    }
    trace("登录成功[{$sjhm}][{$aqmm}]");
    Session::set('HTOAUTH.AUID', $Agent['UserID']);
    return result([], 0, '登录成功');
  }
  /**
   *  @brief  : 推广员申请页面&&表单处理
   *  @return : page|JSON
   *  @details:
   */
  public function registerAction() {
    if ($this->request->isGet()) { // 页面
      return $this->fetch('', []);
    }
    //////////// 表单处理 ////////////
    //--- 验证器验证, 按照顺序逐一判断 ---
    $retn = $this->validate($_REQUEST, [
      'zsxm|真实姓名' => 'require|length:1,10|chsAlpha',
      // 'sfzh|身份证号' => 'require|regex:/^[0-9Xx]{15,18}$/',
      'aqmm|安全密码' => 'require|regex:/^[\S]{6,16}$/',
      'sjhm|手机号码' => 'require|mobile',
    ]);
    if (true !== $retn) {
      return result([], 101, $retn);
    }
    //--- 数据库验证 ---
    $zsxm = $this->request->param('zsxm/s', '', 'trim');
    $sfzh = $this->request->param('sfzh/s', '', 'trim');
    $aqmm = $this->request->param('aqmm/s', '', 'trim');
    $sjhm = $this->request->param('sjhm/s', '', 'trim');

    $Agent = table('AgentReg', 'rydb.websms')->where(['Channel' => $this->Channel, 'MobilePhone' => $sjhm])->find();
    if (!empty($Agent)) { // 手机号存在
      if ($Agent['Status'] == 0) {
        return result([], 102, '此手机号正在审核中');
      }
      return result([], 103, '此手机号已被使用');
    } else { // 手机号不存在
      try {
        if (empty($this->user['unionid'])) {
          $OpenID = md5(uniqid(mt_rand(), true));
        } else {
          $OpenID = $this->user['unionid'];
        }
        $data = [
          'Compellation'=> $zsxm,
          'PassPortID'  => $sfzh,
          'MobilePhone' => $sjhm,
          'WeiXin'      => trim($this->user['nickname'] ?? ''),
          'LogonPass'   => $aqmm,
          'IP'          => $this->request->ip(),
          'OpenID'      => $OpenID,
          'Sex'         => $this->user['sex'] ?? 0,
          'HeadImgUrl'  => $this->user['headimgurl'] ?? '',
          'CityAddress' => ($this->user['country'] ?? '').':'.($this->user['province'] ?? '').':'.($this->user['city'] ?? ''),
          'Updatetime'  => new Expression('GETDATE()'),
          'Addtime'     => new Expression('GETDATE()'),
          'Channel'     => $this->Channel,
        ];
        table('AgentReg', 'rydb.websms')->insert($data);
      } catch (Exception $e) {
        trace([$e->getCode(), $e->getMessage()]);
        return result([], 103, '申请失败, 请联系在线客服!');
      }
      return result([], 0, '申请成功, 请耐心等待审核!');
    }
    return result([], 1, '执行失败, 请稍后再试!');
  }
  /**
   *  @brief  : 我的信息
   *  @return : page
   *  @details:
   */
  public function myinfoAction() {
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    $TotalAll = table('UserRoomCard', 'rydb.treasure')->where(['SpreaderID' => $Agent['UserID'], 'KindID' => 0])->count();
    return $this->fetch('', [
      'Agent'     => $Agent,
      'TotalAll'  => $TotalAll,   // 共计
    ]);
  }
  /**
   *  @brief  : 房卡充值页面|房卡充值记录
   *  @return : page|JSON
   *  @details: 代理给玩家充值房卡
   */
  public function payAction() {

    $Agent = table('RYWebSMSDB.dbo.AgentReg a', 'rydb.websms')
             ->field(['a.UserID', 'a.GameID', 'a.Channel', 'ISNULL(b.RoomCard, 0)' => 'RoomCard'])
             ->join('RYTreasureDB.dbo.UserRoomCard b', 'b.UserID = a.UserID AND KindID = 0', 'LEFT')
             ->where('a.UserID', $this->auid)->find();

    $info = [
      'RoomCard' => $Agent['RoomCard'],
      'Today' => table('RecordRoomCard', 'rydb.record')->where(['TypeID'=>11, 'SourceUserID'=>$Agent['UserID']])->whereTime('CollectDate', 'today')->sum('RoomCard'),
      'Week'  => table('RecordRoomCard', 'rydb.record')->where(['TypeID'=>11, 'SourceUserID'=>$Agent['UserID']])->whereTime('CollectDate', 'week')->sum('RoomCard'),
      'Month' => table('RecordRoomCard', 'rydb.record')->where(['TypeID'=>11, 'SourceUserID'=>$Agent['UserID']])->whereTime('CollectDate', 'month')->sum('RoomCard'),
    ];

    $total = table('RYRecordDB.dbo.RecordRoomCard a', 'rydb.record')->field([
      'a.RoomCard','a.CollectDate','c.NickName','c.GameID',
    ])
    ->join('RYAccountsDB.dbo.AccountsInfo b', 'a.SourceUserID = b.UserID', 'LEFT')
    ->join('RYAccountsDB.dbo.AccountsInfo c', 'a.TargetUserID = c.UserID', 'LEFT')
    ->where(['a.TypeID'=>11, 'a.SourceUserID|a.TargetUserID'=>$Agent['UserID']])
    ->count();

    if ($total > 0) {
      $rows = table('RYRecordDB.dbo.RecordRoomCard a', 'rydb.record')->field([
        'a.RoomCard','a.CollectDate','c.NickName','c.GameID',
      ])
      ->join('RYAccountsDB.dbo.AccountsInfo b', 'a.SourceUserID = b.UserID', 'LEFT')
      ->join('RYAccountsDB.dbo.AccountsInfo c', 'a.TargetUserID = c.UserID', 'LEFT')
      ->where(['a.TypeID'=>11, 'a.SourceUserID|a.TargetUserID'=>$Agent['UserID']])
      ->order(['CollectDate'=>'DESC'])
      ->page($this->pageCurrent, $this->pageSize)
      ->select();
    }
    $retn = [
      'rows'  => $rows ?? [],
      'total'=> $total ?? 0,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
      'info' => $info ?? [],
    ];
    if ($this->request->isPost()) {
      return result($retn, 0);
    } else {
      // 转账面额常量
      $CARDS = table('CardCoin', 'rydb.websms')->field(['ID', 'RMB', 'Coin', 'Zeng'])->where(['Type' => 1, 'State' => 1, 'Channel'=>$this->Channel])->order('RMB')->select();
      $retn['info']['CARDS'] = $CARDS;
      return $this->fetch('', $retn);
    }
  }
  /**
   *  @brief  : 代理给玩家充值房卡AJAX
   *  @return : JSON
   *  @details:
   */
  public function pay2Action() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    ////////////////////////////////////////////////////////////////////////////
    $Card = [];
    $CardID = $this->request->param('CardID/d', 0);
    if ($CardID > 0) {
      $Card = table('CardCoin', 'rydb.websms')->where(['Type' => 1, 'State' => 1, 'Channel'=>$this->Channel, 'ID' => $CardID])->find();
    }
    if (empty($Card)) {
      return result([], 101, '卡无效');
    }
    ////////////////////////////////////////////////////////////////////////////
    $GameID = $this->request->param('GameID/d', 0);
    if ($GameID <= 0) {
      return result([], 102, 'GameID无效');
    }
    $Agent = table('RYWebSMSDB.dbo.AgentReg a', 'rydb.websms')
             ->field(['a.UserID', 'a.GameID', 'a.Channel', 'ISNULL(b.RoomCard, 0)' => 'RoomCard'])
             ->join('RYTreasureDB.dbo.UserRoomCard b', 'b.UserID = a.UserID AND KindID = 0', 'LEFT')
             ->where('a.UserID', $this->auid)->find();

    if ($Agent['GameID'] == $GameID) {
      return result([], 103, '自已不能给自已充值');
    }
    $User = table('RYAccountsDB.dbo.AccountsInfo a', 'rydb.accounts')
            ->field(['a.UserID', 'a.GameID', 'a.Channel', 'a.AccountsType', 'ISNULL(b.RoomCard, 0)' => 'RoomCard'])
            ->join('RYTreasureDB.dbo.UserRoomCard b', 'b.UserID = a.UserID AND KindID = 0', 'LEFT')
            ->where('a.GameID', $GameID)
            ->find();

    if (empty($User)) {
      return result([], 104, '接收用户不存在');
    }
    if ($User['Channel'] != $Agent['Channel']) {
      return result([], 105, '接收用户不在同一渠道内');
    }
    if ($User['AccountsType'] == 1) {
      return result([], 106, '代理之间不能相互充值房卡');
    }
    if ($Agent['RoomCard'] < $Card['Coin']) {
      return result([], 107, '您的房卡数量少于转帐数量');
    }

    // 代理扣房卡
    $eax = table('UserRoomCard', 'rydb.treasure')->where(['UserID'=>$Agent['UserID'], 'KindID'=>0])->setDec('RoomCard', $Card['Coin']);
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'KindID'    => 0,
      'dwUserID'  => $Agent['UserID'],
      'dwCost'    => $Card['Coin'] * -1,
      'dwCostType'=> 1027,
      'describe'  => sprintf('代充扣除:%d 剩余房卡:%d', $Card['Coin'] * -1, $Agent['RoomCard'] - $Card['Coin']),
      'beleftRoomCard'=> $Agent['RoomCard'] - $Card['Coin'],
    ]);

    // 用户加房卡
    $eax = table('UserRoomCard', 'rydb.treasure')->where(['UserID' => $User['UserID'], 'KindID' => 0])->setInc('RoomCard', $Card['Coin'] + $Card['Zeng']);
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'KindID'    => 0,
      'dwUserID'  => $User['UserID'],
      'dwCost'    => $Card['Coin'] + $Card['Zeng'],
      'dwCostType'=> 1028,
      'describe'  => sprintf('代充到账:%d+%d 剩余房卡:%d', $Card['Coin'], $Card['Zeng'], $User['RoomCard'] + $Card['Coin'] + $Card['Zeng']),
      'beleftRoomCard'=> $User['RoomCard'] + $Card['Coin'] + $Card['Zeng'],
    ]);

    $eax = table('RecordRoomCard', 'rydb.record')->insert([ // 记录代充明细
      'SourceUserID'=> $Agent['UserID'],
      'TargetUserID'=> $User['UserID'],
      'RoomCard'    => $Card['Coin'],
      'SBeforeCard' => $Agent['RoomCard'],
      'TBeforeCard' => $User['RoomCard'],
      'TypeID'      => 11,
      'ClientIP'    => $this->request->ip(),
      'Remarks'     => '代理给玩家充值房卡',
    ]);

    $info = [
      'RoomCard' => $Agent['RoomCard'] - $Card['Coin'],
      'Today' => table('RecordRoomCard', 'rydb.record')->where(['TypeID' => 11, 'SourceUserID' => $Agent['UserID']])->whereTime('CollectDate', 'today')->sum('RoomCard'),
      'Week'  => table('RecordRoomCard', 'rydb.record')->where(['TypeID' => 11, 'SourceUserID' => $Agent['UserID']])->whereTime('CollectDate', 'week')->sum('RoomCard'),
      'Month' => table('RecordRoomCard', 'rydb.record')->where(['TypeID' => 11, 'SourceUserID' => $Agent['UserID']])->whereTime('CollectDate', 'month')->sum('RoomCard'),
    ];
    return result($info, 0);
  }
  /**
   *  @brief  : 推广员在线充值
   *  @return : page|JSON
   *  @details: 推广员自助充值房卡
   */
  public function webpayAction() {

    $Agent = table('AgentReg', 'rydb.websms')->field(['UserID', 'GameID', 'Channel', 'PayLv'])->where('UserID', $this->auid)->find();
    $Agent['RoomCard'] = table('UserRoomCard', 'rydb.treasure')->where(['UserID' => $Agent['UserID'], 'KindID' => 0])->value('RoomCard');
    $CARDS = table('CardCoin', 'rydb.websms')->field(['ID', 'RMB', 'Coin', 'Zeng', 'Remark'])->where(['Type' => 2, 'State' => 1, 'Channel' => $this->Channel, 'KindID' => $Agent['PayLv']])->order('RMB')->select();
    $info = [
      'RoomCard' => $Agent['RoomCard'],
    ];

    $conds = [
      'UserID'    => $this->auid,
      'Status'    => 1,
      'GameStatus'=> 1,
      ['EXP', new Expression('DATEDIFF(DAY, Updatetime, GETDATE()) <= 30')],
    ];

    $total = table('ChargeOnline', 'rydb.websms')->where($conds)->count();
    if($total>0){
      $rows = table('ChargeOnline', 'rydb.websms')->field([
        'ID', "('*' + RIGHT(MerBillNo, 5))" => 'MerBillNo', 'RMB', 'Addtime',
      ])
      ->where($conds)->page($this->pageCurrent, $this->pageSize)
      ->order(['Addtime' => 'DESC'])->select();
    }
    $retn = [
      'rows' => $rows ?? [],
      'total'=> $total ?? 0,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
      'info' => $info ?? [],
    ];
    if ($this->request->isPost()) {
      return result($retn, 0);
    } else {
      ////微信公众号网页JSSDK验证参数///////////////////////////////////////
      $wapi = new Wechat($this->conf);
      $furl = $this->request->url(true); // 当前页面完整URL
      $sign = $wapi->getJsSign($furl);
      if (empty($sign)) {
        trace(['errno' => $wapi->errCode, 'error' => $wapi->errMsg]);
        $sign = [];
      }
      $retn['info']['sign'] = $sign;
      $retn['info']['CARDS'] = $CARDS;
      //////////////////////////////////////////////////////////////////////
      $host = $this->request->host();
      $flag = explode('.', $host);
      $flag = strtolower($flag[0]);
      $retn['PURL'] = [
        '1' => "http://{$flag}.zf.game654.cn/pay.alipay.h5/apply.html",
        '2' => "http://{$flag}.zf.game654.cn/pay.hee/apply.html",
      ];
      $retn['Agent'] = $Agent;
      return $this->fetch('', $retn);
    }
  }
  /**
   *  @brief  : 在线充值-生成订单AJAX
   *  @return : JSON
   *  @details:
$.req({
  url: "{:url('WebPayOrder')}?CardID=" + card.ID,
  success: function (resp, status, xhr) {
    avalon.log(resp);
    if (resp.errno != 0) {
      $.alert(resp.error);
      return;
    }
    wx.chooseWXPay({
      timestamp: resp.data.timeStamp,
      nonceStr: resp.data.nonceStr,
      package: resp.data.package,
      signType: resp.data.signType,
      paySign: resp.data.paySign,
      success: function (e) {
        vm.ajaxPage(1);
      },
      fail: function (e) {
        alert('wx.chooseWXPay.fail:' + JSON.stringify(e));
      },
      complete: function (e) {
        // alert('wx.chooseWXPay.complete:' + JSON.stringify(e));
      },
      cancel: function (e) {
        // alert('wx.chooseWXPay.cancel:' + JSON.stringify(e));
      }
    });
  }
});
   */
  public function WebPayOrderAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    ////////////////////////////////////////////////////////////////////////////
    $Card = [];
    $CardID = $this->request->param('CardID/d', 0);
    if ($CardID > 0) {
      $Card = table('CardCoin', 'rydb.websms')->where(['Type' => 2, 'State' => 1, 'Channel'=>$this->Channel, 'ID' => $CardID])->find();
    }
    if (empty($Card)) {
      return result([], 101, '卡无效');
    }

    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    ////////////////////////////////////////////////////////////////////////////
    $mapi = new MchApi($this->conf);
    $nurl = url('Notify/WxPay', '', true, true);
    $tradNo = MchApi::MakeTradeNo();
    $order = $mapi->UnifiedOrder([ // 调用统一下单接口
      'body'      => '游戏充值',
      'trade_type'=> 'JSAPI',
      'total_fee' => intval($Card['RMB'] * 100), // 整数, 单位为分
      'notify_url'=> $nurl,
      'openid'    => $this->user['openid'],
      'out_trade_no' => $tradNo,
      'attach'  => json_encode(['UserID'=>$Agent['UserID'], 'CardID'=>$CardID], JSON_UNESCAPED_UNICODE),
    ]);
    if (!isset($order['prepay_id'])) {
      return result([], 102, '统一下单失败');
    }

    $retn = [
      'appId'     => $this->conf['AppID'] ?? '',
      'timeStamp' => time(),
      'nonceStr'  => MchApi::UUID(),
      'package'   => "prepay_id={$order['prepay_id']}",
      'signType'  => 'MD5',
    ];
    $retn['paySign'] = $mapi->MakeSign($retn);
    trace($retn);
    $eax = table('ChargeOnline', 'rydb.websms')->insert([
      'GameID'    => $Agent['GameID'],
      'UserID'    => $Agent['UserID'],
      'MerBillNo' => $tradNo,
      'RMB'       => $Card['RMB'],
      'Addtime'   => new Expression('GETDATE()'),
      'Updatetime'=> new Expression('GETDATE()'),
      'PayType' => 'wxgzh',
      'wwwType' => $this->request->host(),
      'wwwIp'   => $this->request->ip(),
    ]);
    return result($retn, 0);
  }
  /**
   *  @brief  : 邀请记录
   *  @return : page|JSON
   *  @details: 获取当前推广员的玩家绑定记录
   */
  public function inviteAction() {
    $auid = $this->request->param('auid/d', 0);
    $auid = $auid <=0 ? $this->auid : $auid;

    $total = 0;
    $info = [];
    $rows = [];
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $auid)->find();
    if (!empty($Agent)) {
      $conds = ['a.SpreaderID' => $Agent['UserID']];
      //////////////////////////////////////////////////////////////////////////
      $total = table('UserRoomCard a', 'rydb.treasure')->where($conds)->count();
      if ($total > 0) {
        $rows = table('UserRoomCard a', 'rydb.treasure')->field([
          'a.UserID', 'a.KindID', 'a.SpreaderID', 'a.SpreaderIDBindTime' => 'BindTime',
          'b.GameID', 'b.NickName', 'b.Gender',
        ])
        ->join('RYAccountsDB.dbo.AccountsInfo b', 'b.UserID = a.UserID', 'LEFT')
        ->where($conds)
        ->order(['BindTime' => 'DESC'])
        ->page($this->pageCurrent, $this->pageSize)
        ->select();

        $info['Month'] = table('UserRoomCard a', 'rydb.treasure')->where($conds)->whereTime('SpreaderIDBindTime', 'month')->count();
        $info['Week']  = table('UserRoomCard a', 'rydb.treasure')->where($conds)->whereTime('SpreaderIDBindTime', 'week')->count();
        $info['Today'] = table('UserRoomCard a', 'rydb.treasure')->where($conds)->whereTime('SpreaderIDBindTime', 'today')->count();
      }
    }
    ////////////////////////////////////////////////////////////////////////////
    $retn = [
      'auid' => $auid,
      'rows' => $rows,
      'total'=> $total,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
      'info' => $info,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief  : 我的佣金
   *  @return : page|JSON
   *  @details: 获取当前推广员的返点记录(包含下级的返点)
   */
  public function rebateAction() {
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    if (!empty($Agent)) {
      $aa = date('Y-m-d H:i:s', strtotime('first Day of this month 00:00:00'));
      $bb = date('Y-m-d H:i:s', strtotime('first Day of next month 00:00:00'));

      $conds = [
        'a.AgentID'   => $Agent['UserID'],
        'a.IsDisable' => 0,
        'b.Status'    => 1,
        'b.GameStatus'=> 1,
        'a.Addtime'   => new Expression("> c.RebateTime AND (a.Addtime BETWEEN '{$aa}' AND '{$bb}')"),
      ];

      ////////////////////////////////////////////////////////////////////////////////////
      $total = table('RYWebSMSDB.dbo.AgentChargeRebate a', 'rydb.websms')
              ->distinct(true)->field('b.MerBillNo')
              ->join('RYWebSMSDB.dbo.ChargeOnline b', 'b.MerBillNo = a.MerBillNo', 'LEFT')
              ->join('RYWebSMSDB.dbo.AgentReg c', 'c.UserID = a.AgentID', 'LEFT')
              ->where($conds)
              ->count();

      if ($total > 0) {
        $sql2 = table('RYWebSMSDB.dbo.ChargeOnline b', 'rydb.websms')
                ->field(['b.UserID', 'b.MerBillNo', 'b.Status', 'b.GameStatus'])
                ->where(['b.Status' => 1, 'b.GameStatus' => 1])
                ->group('b.UserID, b.MerBillNo, b.Status, b.GameStatus')
                ->buildSql();

        $rows = table('RYWebSMSDB.dbo.AgentChargeRebate a', 'rydb.websms')->field([
                  'a.ID', 'a.RMB', 'a.myRebate', 'a.Addtime', 'd.NickName',
                ])
                ->join("{$sql2} b", 'b.MerBillNo = a.MerBillNo')
                ->join('RYWebSMSDB.dbo.AgentReg c', 'c.UserID = a.AgentID', 'LEFT')
                ->join('RYAccountsDB.dbo.AccountsInfo d', 'd.UserID = b.UserID', 'LEFT')
                ->where($conds)
                ->order(['Addtime' => 'DESC'])
                ->page($this->pageCurrent, $this->pageSize)
                ->select();

        ///////合计业绩|合计佣金///////
        $info = table('RYWebSMSDB.dbo.AgentChargeRebate a', 'rydb.websms')->field([
          'SUM(a.RMB)'=>'RMB', 'SUM(a.myRebate)'=>'Rebate'
        ])
        ->join("{$sql2} b", 'b.MerBillNo = a.MerBillNo')
        ->join('RYWebSMSDB.dbo.AgentReg c', 'c.UserID = a.AgentID', 'LEFT')
        ->where($conds)
        ->find();
        ///////下级业绩|下级佣金///////
        $suba = table('RYWebSMSDB.dbo.AgentChargeRebate a', 'rydb.websms')->field([
          'SUM(a.RMB)'=>'RMB', 'SUM(a.myRebate)'=>'Rebate'
        ])
        ->join("{$sql2} b", 'b.MerBillNo = a.MerBillNo')
        ->join('RYWebSMSDB.dbo.AgentReg c', 'c.UserID = a.AgentID', 'LEFT')
        ->where($conds)
        ->where(['a.myAgentLevel' => new Expression('= (c.AgentLevel + 1)')])
        ->find();
      }
    }
    ////////////////////////////////////////////////////////////////////////////
    $retn = [
      'rows' => $rows??[],
      'info' => $info??[],
      'suba' => $suba??[],
      'total'=> $total??0,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief  : 下级佣金
   *  @return : page
   *  @details:
   */
  public function agentAction() {
    return $this->fetch('', []);
  }
  /**
   *  @brief  : 代理级别
   *  @return : page
   *  @details:
   */
  public function subagentAction() {
    $conds = ['a.Status'=>1];
    $order = [];
    ////////////////////////////////////////////////////////////////////////////
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    if (!empty($Agent)) {
      $conds['a.ParentId'] = $this->auid;
      ///////////////////////////////////
      $total = table('RYWebSMSDB.dbo.AgentReg a', 'rydb.websms')->where($conds)->count();
      if ($total > 0) {
        $rows = table('RYWebSMSDB.dbo.AgentReg a', 'rydb.websms')->field([
          'a.UserID','a.GameID','a.Compellation','a.AgentLevel','a.IsDirect','a.DirectLevel',
          'a.level0','a.level1','a.level2','a.level3','a.level4','a.level5','a.level6',
          '( SELECT COUNT (UserID) FROM RYAccountsDB.dbo.AccountsInfo WHERE SpreaderID = a.UserID )'=>'TotalBind',
          '( SELECT ISNULL(SUM(c.RMB), 0) FROM dbo.AgentReg AS b LEFT JOIN dbo.AgentChargeRebate c ON c.AgentID = b.UserID WHERE b.UserID = a.UserID AND c.IsDisable = 0 AND c.Addtime > b.RebateTime )'=>'TotalRebate',
        ])
        ->where($conds)
        ->order($order)
        ->page($this->pageCurrent, $this->pageSize)
        ->select();

        if (!empty($rows)) {
          $lvs = ['一', '二', '三', '四', '五', '六'];
          foreach($rows as & $row) {
            if ($row['IsDirect']) {
              // $row['pv'] = $row['DirectLevel'];
              $lv = $row['AgentLevel'] - 1;
              $row['pv'] = $row["level{$lv}"] ?? 0;
              $row['lv'] = '直销';
            } else {
              $lv = $row['AgentLevel'] - 1;
              $row['pv'] = $row["level{$lv}"] ?? 0;
              $row['lv'] = (array_key_exists($lv, $lvs) ? $lvs[$lv] : $lv).'级';
            }
            unset($row['level0'], $row['level1'], $row['level2'], $row['level3'], $row['level4'], $row['level5'], $row['level6']);
            unset($row['ROW_NUMBER'], $row['IsDirect'], $row['DirectLevel']);
            unset($row['Compellation'], $row['AgentLevel']);
          }
        }
      }
      $TotalBind = table('RYWebSMSDB.dbo.AgentReg a', 'rydb.websms')
        ->join('RYAccountsDB.dbo.AccountsInfo b', 'b.SpreaderID = a.UserID', 'LEFT')
        ->where($conds)
        ->count('b.UserID');

      $TotalRebate = table('RYWebSMSDB.dbo.AgentReg a', 'rydb.websms')
        ->join('RYWebSMSDB.dbo.AgentChargeRebate c', 'c.AgentID = a.UserID', 'LEFT')
        ->where($conds)
        ->where(['c.IsDisable' => 0, 'c.Addtime' => new Expression('> a.RebateTime')])
        ->sum('c.RMB');

      $info = [
        'RMB'   => $TotalBind,
        'Rebate'=> $TotalRebate,
      ];
    }
    ////////////////////////////////////////////////////////////////////////////
    $retn = [
      'rows' => $rows ?? [],
      'info' => $info ?? [],
      'total' => $total ?? 0,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief  : 查询推广员当前返点
   *  @param [in] $GameID : 邀请码
   *  @return : number
   *  @details:
   */
  protected static function getAgentRebate($GameID) {
    $retn = table('AgentReg a', 'rydb.websms')
      ->field(['ISNULL(SUM(b.myRebate), 0)' => 'mRebate'])
      ->join('AgentChargeRebate b', 'a.UserID = b.AgentID', 'LEFT')
      ->where(['b.IsDisable' => 0, 'a.GameID' => $GameID, 'b.Addtime' => new Expression('> a.RebateTime')])
      ->find();
    return $retn['mRebate'] * 1;
  }
  /**
   *  @brief  : 自助提现&&提现历史记录&&分页查询
   *  @return : page|JSON
   *  @details
   */
  public function weixinAction() {
    $Agent = table('AgentReg', 'rydb.websms')->field(['UserID','GameID','Compellation'])->where('UserID', $this->auid)->find();
    $total = 0;
    $rows = [];
    if(!empty($Agent)) {
      $Agent['rebate'] = self::getAgentRebate($Agent['GameID']);  // 推广员当前返点
      $this->pageCurrent = 1;
      $this->pageSize = 1;
      $rows = table('RYWebSMSDB.dbo.AgentRebate', 'rydb.websms')->field(['RMB', 'CollectDate',])
              ->where(['UserID' => $Agent['UserID']])
              ->order(['CollectDate' => 'DESC'])
              ->page($this->pageCurrent, $this->pageSize)
              ->select();
      $total = count($rows);
    }
    ////////////////////////////////////////////////////////////////////////////
    $retn = [
      'info' => $Agent??[],
      'rows' => $rows,
      'total'=> $total,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief  : 提现订单输入确认
   *  @return : page
   *  @details:
   */
  public function cashconfirmAction() {
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    $mRebate = self::getAgentRebate($Agent['GameID']); // 推广员当前返点
    $Agent['mRebate'] = $mRebate;
    $CashMin = table('WxGzh', 'rydb.websms')->where('AppID', $this->conf['AppID'])->value('CashMin');
    return $this->fetch('', [
      'Agent'   => $Agent,
      'CashMin' => $CashMin * 1,
    ]);
  }
  /**
   *  @brief  : 提现佣金
   *  @return : JSON
   *  @details:
   */
  public function cashAction() {

    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }

    $money = $this->request->param('money/f', 0);
    if ($money <= 0) {
      return result([], 101, '提现金额输入有误');
    }
    $money = floor($money * 100) / 100; // 精确保留2位, 不四舍五入

    $CashConfig = table('WxGzh', 'rydb.websms')->where('AppID', $this->conf['AppID'])->find();

    $CashMin = $CashConfig['CashMin'] ?? 0;
    if ($CashMin > 0 && $money < $CashMin) {
      return result([], 102, "提现金额最低{$CashMin}元");
    }

    if ($CashConfig['CashCase'] <= 0) {
      return result([], 103, '通道维护暂停提现');
    }
    if ($money > $CashConfig['CashPool']) {
      return result([], 104, '提现失败, 请稍后再试!');
    }

    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    $Agent['mRebate'] = self::getAgentRebate($Agent['GameID']); // 推广员当前返点

    if ($money > $Agent['mRebate']) {
      return result([], 105, '提现金额超过余额');
    }

    ////////////////////////////////////////////////////////////////////////////
    try {
      $mapi = new MchApi($this->conf);
      $tradNo = MakeTradeNo();
      $retn = $mapi->CashPocket([
        'openid'        => $this->user['openid'], // 谁登陆谁提现
        'check_name'    => false, // 不强校验真实姓名
        'amount'        => $money * 100, // 付款金额, 单位为分
        'desc'          => "{$Agent['Compellation']}, 恭喜发财!",
        'partner_trade_no' => $tradNo,
      ]);
      if ($retn['result_code'] == 'FAIL') { // 支付失败
        if ($retn['err_code'] == 'SYSTEMERROR') { // 系统繁忙
          // 支付失败&&系统繁忙, 查询订单确认
          $bill = $mapi->GetCashPocketTransferInfo($tradNo);
          if ($bill['result_code'] == 'FAIL') { // 支付失败&&查询失败
            return result([], 110, $bill['err_code_des']);
          } else { // 支付失败&&查询成功
            // SUCCESS:转账成功; FAILED:转账失败; PROCESSING:处理中
            if (!in_array($bill['status'], ['SUCCESS', 'PROCESSING'])) {
              return result([], 0, '转账失败, 请稍后再试!');
            }
          }
        } else {
          return result([], 111, $retn['err_code_des']);
        }
      }

      ////// 支付成功 || 订单状态为`转账成功`/`处理中` //////
      // 减少佣金池
      table('WxGzh', 'rydb.websms')->where('AppID', $this->conf['AppID'])->setDec('CashPool', $money);
      // 更新/最后提现金额/最后提现时间
      table('AgentReg', 'rydb.websms')->where('UserID', $Agent['UserID'])->update([
        'RebateRMB'   => $money,  // 最后提现金额
        'RebateTime'  => new Expression('GETDATE()'), // 最后提现时间
      ]);
      // 增加提现记录
      table('AgentRebate', 'rydb.websms')->insert([
        'UserID'  => $Agent['UserID'],
        'RMB'     => $money,
        'Remarks' => $tradNo,
        'CollectDate' => new Expression('GETDATE()'),
      ]);
      return result([], 0, '提现成功, 请注意查收!');
    } catch (Exception $e) {
      trace($e->getMessage());
      return result([], 120, '系统繁忙, 请稍后再试!');
    }
    ////////////////////////////////////////////////////////////////////////////
    return result([], 121, '提现失败!');
  }
  /**
   *  @brief  : 退出登陆
   *  @return :
   *  @details:
   */
  public function exitAction() {
    Session::delete ('HTOAUTH.AUID');
    return $this->redirect(url('index'));
  }
  /**
   *  @brief  : 我的邀请二维码
   *  @return : page
   *  @details:
   */
  public function myqrcAction() {
    return $this->fetch('', []);
  }
  /**
   *  @brief  : 我的邀请二维码
   *  @return : image
   *  @details:
   */
  public function myqrimgAction() {
    return;
  }
  /**
   *  @brief  :
   *  @return :
   *  @details:
   */
  public function familyAction() {
    $conds = [
      'b.AUID'  => $this->auid,
      'a.Status'=> 1,
    ];
    $order = ['ID'=>'DESC'];
    $rows = [];
    ////////////////////////////////////////////////////////////////////////////
    $total = table('RYWebSMSDB.dbo.FamilyMember a', 'rydb.websms')
            ->join('RYWebSMSDB.dbo.Family b', 'b.ID = a.FamilyID', 'LEFT')
            ->join('RYWebSMSDB.dbo.AgentReg c', 'c.UserID = b.AUID', 'LEFT')
            ->join('RYAccountsDB.dbo.AccountsInfo d', 'd.UserID = a.MemberUID', 'LEFT')
            ->join('RYAccountsDB.dbo.IndividualDatum e', 'e.UserID = a.MemberUID', 'LEFT')
            ->where($conds)->count();
    if ($total > 0) {
      $rows = table('RYWebSMSDB.dbo.FamilyMember a', 'rydb.websms')->field([
        'a.ID', 'd.GameID', 'd.UserID', 'd.NickName', "ISNULL(e.HeadImgUrl,'')"=>'Avatar',
        'ISNULL((SELECT c.GameID FROM RYWebSMSDB.dbo.AgentReg c WHERE c.UserID = d.SpreaderID AND d.SpreaderID > 0), 0)'=>'SID',
      ])
      ->join('RYWebSMSDB.dbo.Family b', 'b.ID = a.FamilyID', 'LEFT')
      ->join('RYWebSMSDB.dbo.AgentReg c', 'c.UserID = b.AUID', 'LEFT')
      ->join('RYAccountsDB.dbo.AccountsInfo d', 'd.UserID = a.MemberUID', 'LEFT')
      ->join('RYAccountsDB.dbo.IndividualDatum e', 'e.UserID = a.MemberUID', 'LEFT')
      ->where($conds)
      ->order($order)
      ->page($this->pageCurrent, $this->pageSize)
      ->select();
    }
    ////////////////////////////////////////////////////////////////////////////
    $retn = [
      'rows' => $rows??[],
      'total'=> $total??0,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief  : 查询玩家与推广员绑定情况
   *  @return : JSON
   *  @details:
   */
  public function qabAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $GameID = $this->request->param('GameID/d', 0);
    if ($GameID <= 0) {
      return result([], 101, '查询参数输入有误');
    }
    $usr = table('RYAccountsDB.dbo.AccountsInfo', 'rydb.accounts')->field([
      'UserID', 'GameID', 'SpreaderID', 'Channel',
    ])->where(['GameID' => $GameID, 'Channel' => $this->Channel])->find();

    if (empty($usr)) {
      return result([], 102, '此ID不存在');
    }
    return result([], 0, $usr['SpreaderID'] > 0 ? "此ID已绑定" : "此ID未绑定");
  }
  /**
   *  @brief  : 家园关系绑定
   *  @return : JSON
   *  @details:
   */
  public function bfmAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $GameID = $this->request->param('GameID/d', 0);
    if ($GameID <= 0) {
      return result([], 101, '查询参数输入有误');
    }
    $User = table('AccountsInfo', 'rydb.accounts')->field([
      'UserID', 'GameID', 'SpreaderID', 'Channel',
    ])->where(['GameID' => $GameID, 'Channel' => $this->Channel])->find();

    if (empty($User)) {
      return result([], 102, '此ID不存在');
    }

    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    $eax = FamilyBind($User['UserID'], $this->auid); // 建立家园关系
    return result([], 0, '添加成功');
  }
  /**
   *  @brief  : 删除家族成员
   *  @return : JSON
   *  @details:
   */
  public function FamilyMemberDeleteAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $id = $this->request->param('id/d', 0);
    if ($id <= 0) {
      return result([], 101, '业务参数输入有误');
    }
    $BossID = $this->auid;
    ////////////////////////////////////////////////////////////////////////////
    $User = table('FamilyMember a', 'rydb.websms')
      ->field(['a.ID', 'a.MemberUID' => 'UserID', 'b.AUID' => 'BossID'])
      ->join('Family b', 'b.ID = a.FamilyID', 'LEFT')
      ->join('AgentReg c', 'c.UserID = b.AUID', 'LEFT')
      ->where(['a.ID' => $id])
      ->find();

    if (!empty($User)) {
      if ($User['BossID'] == $BossID) { // 家园关系属于当前推广员
        ////////////////////////////////////////////////////////////////
        table('FamilyMember', 'rydb.websms')->where('ID', $id)->update([
          'Status'    => 0,
          'UpdateTime'=> new Expression('GETDATE()'),
        ]);
      }
    }
    return result([], 0, '删除成功');
  }
  /**
   *  @brief  : 修改密码
   *  @return : page|JSON
   *  @details:
   */
  public function resetpwdAction() {
    if ($this->request->isGet()) {
      return $this->fetch('', []);
    } else if ($this->request->isPost()) {
      //--- 验证器验证, 按照顺序逐一判断 ---
      $retn = $this->validate($_POST, [
        'pwd1|密码1' => 'require|length:6,16|regex:/^[\S]{6,16}$/',
        'pwd2|密码2' => 'require|length:6,16|regex:/^[\S]{6,16}$/|confirm:pwd1',
      ]);
      if (true !== $retn) {
        return result([], 101, $retn);
      }
      $pwd1 = $this->request->param('pwd1/s', '');
      $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
      $eax = table('AgentReg', 'rydb.websms')->where('ID', $Agent['ID'])->setField('LogonPass', $pwd1);
      return result([], 0, '');
    }
  }
  /**
   *  @brief  : 群组管理
   *  @return : page|JSON
   *  @details:
   */
  public function qunmgrAction() {
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    $rows = [];
    $total = 0;
    if (!empty($Agent['AssoFamily'])) {
      $conds = ['a.State' => 1, 'a.Code' => ['IN', $Agent['AssoFamily']]];
      $total = table('Family a', 'rydb.websms')->where($conds)->count();
      if ($total > 0) {
        $rows = table('Family a', 'rydb.websms')->field([
            'a.ID', 'a.AUID' => 'UserID', 'a.Code', 'b.GameID', 'b.NickName',
            "ISNULL(c.HeadImgUrl, '')" => 'Avatar',
            '(SELECT COUNT(ID) FROM RYWebSMSDB.dbo.FamilyMember d WHERE d.FamilyID = a.ID)' => 'TotalMember',
            '(SELECT ISNULL(e.RoomCard, 0) FROM RYTreasureDB.dbo.UserRoomCard e WHERE e.KindID = 0 AND e.UserID = a.AUID)' => 'RoomCard',
          ])
          ->join('RYAccountsDB.dbo.AccountsInfo b', 'b.UserID = a.AUID', 'LEFT')
          ->join('RYAccountsDB.dbo.IndividualDatum c', 'c.UserID = a.AUID', 'LEFT')
          ->where($conds)
          ->page($this->pageCurrent, $this->pageSize)
          ->select();
      }
    }
    $retn = [
      'rows' => $rows??[],
      'total'=> $total??0,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief : 群主充值
   *  @return: page
   *  @detail: 
   */
  public function qunbpcAction() {
    $rows = [];
    $total = 0;
    $Info = [];
    $Code = $this->request->param('code/d', 0); // 群号
    if ($Code > 0) {
      $Info = table('Family a', 'rydb.websms')->field([
        'a.AUID' => 'UserID', 'a.Code', 'b.GameID', 'b.NickName', 'a.Caption',
        '(SELECT ISNULL(RoomCard, 0) FROM RYTreasureDB.dbo.UserRoomCard b WHERE b.UserID = a.AUID AND b.KindID = 0)' => 'RoomCard',
      ])
      ->join('RYAccountsDB.dbo.AccountsInfo b', 'b.UserID = a.AUID', 'LEFT')
      ->where(['a.Code' => $Code])->find();
      
      $conds = [
        'Status' => 1, 'GameStatus' => 1, ['EXP', new Expression('DATEDIFF(DAY, Updatetime, GETDATE()) <= 30')],
        'UserID' => $Info['UserID']??0,
      ];
      $total = table('ChargeOnline', 'rydb.websms')->where($conds)->count();
      if ($total > 0) {
        $rows = table('ChargeOnline', 'rydb.websms')->field([
          "('*' + RIGHT(MerBillNo, 5))" => 'MerBillNo', 'RMB', 'Updatetime' => 'PayTime'
        ])
        ->where($conds)
        ->order(['Updatetime' => 'DESC'])
        ->page($this->pageCurrent, $this->pageSize)
        ->select();
      }
    }
    
    $retn = [
      'rows' => $rows,
      'total'=> $total,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
    ];
    if ($this->request->isGet()) {
      
      // 确定充值域名前缀
      $host = $this->request->host();
      $flag = explode('.', $host);
      $flag = strtolower($flag[0]);
      $retn['PURL'] = [
        '1' => "http://{$flag}.zf.game654.cn/pay.alipay.h5/apply.html",
        '2' => "http://{$flag}.zf.game654.cn/pay.hee/apply.html",
      ];
      
      $Agent = table('AgentReg', 'rydb.websms')->field(['UserID', 'GameID', 'Channel', 'PayLv'])->where('UserID', $this->auid)->find();
      $CARDS = table('CardCoin', 'rydb.websms')->field(['ID', 'RMB', 'Coin', 'Zeng', 'Remark'])->where(['Type' => 2, 'State' => 1, 'Channel' => $this->Channel, 'KindID' => $Agent['PayLv']])->order('RMB')->select();
      $retn['Agent'] = $Agent;
      $retn['CARDS'] = $CARDS;
      $retn['Info']  = $Info;
      $retn['Code']  = $Code;
      
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief : 群与代理账号绑定
   *  @return: page|JSON
   *  @detail:
   */
  public function qunmemAction() {

    $rows = [];
    $total = 0;
    $Info = [];
    $code = $this->request->param('code/d', 0); // 群号

    if ($code > 0) {
      $conds = ['a.State' => 1, 'a.Code' => $code, 'b.Status' => 1, 'b.IsPass' => 1, 'b.IsBlack' => 0];
      $search = $this->request->param('search/s', '', 'trim');
      if (!empty($search)) {
        $conds['c.GameID|c.NickName'] = ['LIKE', "%{$search}%"];
      }

      $total = table('Family a', 'rydb.websms')
        ->join('RYWebSMSDB.dbo.FamilyMember b', 'b.FamilyID = a.ID', 'LEFT')
        ->join('RYAccountsDB.dbo.AccountsInfo c', 'c.UserID = b.MemberUID', 'LEFT')
        ->where($conds)
        ->count();

      if ($total > 0) {
        
        $orderMap = [
          'A' => 'NickName',
          'B' => 'Gold',
          'C' => 'TodayCost',
          'D' => 'TotalCost',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'B';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        
        $rows = table('Family a', 'rydb.websms')->field([
          'b.ID', 'b.Gold', 'c.GameID', 'c.NickName', '(CASE WHEN a.AUID = b.MemberUID THEN 1 ELSE 0 END)' =>'IsBoss',
          "ISNULL(d.HeadImgUrl, '')" => 'Avatar',
          '(SELECT ISNULL(SUM (dwCost), 0) FROM RYRecordDB.dbo.CostRoomCardRecord WHERE dwCostType = 6 AND dwUserID = b.MemberUID AND dwCost < 0)' => 'TotalCost',
          '(SELECT ISNULL(SUM (dwCost), 0) FROM RYRecordDB.dbo.CostRoomCardRecord WHERE dwCostType = 6 AND dwUserID = b.MemberUID AND dwCost < 0 AND DATEDIFF(DAY, CostTime, GETDATE()) = 0)' => 'TodayCost',
        ])
        ->join('RYWebSMSDB.dbo.FamilyMember b', 'b.FamilyID = a.ID', 'LEFT')
        ->join('RYAccountsDB.dbo.AccountsInfo c', 'c.UserID = b.MemberUID', 'LEFT')
        ->join('RYAccountsDB.dbo.IndividualDatum d', 'd.UserID = b.MemberUID', 'LEFT')
        ->where($conds)
        ->page($this->pageCurrent, $this->pageSize)
        ->order($order)
        ->select();
      }
      
      $Info = table('Family a', 'rydb.websms')->field([
        'a.AUID' => 'UserID', 'a.Code', 'a.Caption', 'b.GameID', 'b.NickName', 'c.Gold',
      ])
      ->join('RYAccountsDB.dbo.AccountsInfo b', ' b.UserID = a.AUID', 'LEFT')
      ->join('RYWebSMSDB.dbo.FamilyMember c', 'c.FamilyID = a.ID AND c.MemberUID = a.AUID', 'LEFT')
      ->where(['a.State' => 1, 'a.Code' => $code])
      ->find();
    }

    $retn = [
      'rows' => $rows,
      'total'=> $total,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
      'Code' => $code,
      'Info' => $Info,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
  /**
   *  @brief : 调整群成员的房费
   *  @return: JSON
   *  @detail:
   */
  public function zengoldAction() {

    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $Code = $this->request->param('Code/d', 0);
    $GameID = $this->request->param('GameID/d', 0);
    $Gold = $this->request->param('Gold/d', 0);

    if ($Gold <= 0) {
      return result([], 101, '房费数额必须大于0');
    }
    
    $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $this->auid)->find();
    if (empty($Agent['AssoFamily'])) {
      return result([], 101, '你没有所关联群');
    }
    $AssoFamily = explode(',', $Agent['AssoFamily']);
    $eax = 0;
    foreach($AssoFamily as $a => $b) {
      if ($b == $Code) {
        $eax = 1;
        break;
      }
    }
    if ($eax == 0) {
      return result([], 102, "你没有所关联群[{$Code}]");
    }

    $Family = table('Family', 'rydb.websms')->where('Code', $Code)->find();
    if (empty($Family)) {
      return result([], 103, "群[{$Code}]不存在");
    }

    $UserID = table('AccountsInfo', 'rydb.accounts')->where(['GameID' => $GameID])->value('UserID');
    if ($UserID <= 0) {
      return result([], 104, "用户[{$GameID}]不存在");
    }
    $Member = table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $Family['ID'], 'MemberUID' => $UserID])->find();
    if (empty($Member)) {
      return result([], 105, "成员[{$GameID}]与群[{$Code}]的绑定关系不存在");
    }

    $Boss = table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $Family['ID'], 'MemberUID' => $Family['AUID']])->find();
    
    if ($Boss['MemberUID'] == $Member['MemberUID']) {
      return result([], 106, "群主不能给自己划拨房费");
    }
    if ($Boss['Gold'] < $Gold) {
      return result([], 106, '余额不足');
    }
    
    // 减少群主房费
    $eax = table('FamilyMember', 'rydb.websms')->where(['ID' => $Boss['ID']])->setDec('Gold', $Gold);
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'dwUserID'  => $Boss['MemberUID'],
      'dwCost'    => $Gold * -1,
      'dwCostType'=> 6,
      'describe'  => sprintf('房费转出:%d 剩余房费:%d', $Gold * -1, $Boss['Gold'] - $Gold),
      'beleftRoomCard'=> $Boss['Gold'] - $Gold,
    ]);
    
    
    // 增加成员房费
    $eax = table('FamilyMember', 'rydb.websms')->where(['ID' => $Member['ID']])->setInc('Gold', $Gold);
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'dwUserID'  => $Member['MemberUID'],
      'dwCost'    => $Gold,
      'dwCostType'=> 6, 
      'describe'  => sprintf('房费转入:%d 剩余房费:%d', $Gold, $Member['Gold'] + $Gold),
      'beleftRoomCard'=> $Member['Gold'] + $Gold,
    ]);

    $eax = table('RecordRoomCard', 'rydb.record')->insert([ // 记录代充群货币明细
      'SourceUserID'=> $Boss['MemberUID'],
      'TargetUserID'=> $Member['MemberUID'],
      'RoomCard'    => $Gold,
      'SBeforeCard' => $Boss['Gold'],
      'TBeforeCard' => $Member['Gold'],
      'TypeID'      => 11,
      'ClientIP'    => $this->request->ip(),
      'Remarks'     => '群主给玩家划拨房费',
    ]);

    return result([], 0, '赠送成功');
  }
  /**
   *  @brief : 回收成员房费到群主房费中
   *  @return: JSON
   *  @detail:
   */
  public function huishougoldAction(){
    $Code   = $this->request->param('Code/d', 0);
    $GameID = $this->request->param('GameID/d', 0);
    
    // 判断群
    $Family = table('Family', 'rydb.websms')->where('Code', $Code)->find();
    if (empty($Family)) {
      return result([], 103, "群[{$Code}]不存在");
    }
    
    // 确定成员的UserID
    $UserID = table('AccountsInfo', 'rydb.accounts')->where(['GameID' => $GameID])->value('UserID');
    if ($UserID <= 0) {
      return result([], 104, "用户[{$GameID}]不存在");
    }

    $FMBoss = table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $Family['ID'], 'MemberUID' => $Family['AUID']])->find();
    $FMMemb = table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $Family['ID'], 'MemberUID' => $UserID])->find();
    
    if ($FMBoss['MemberUID'] == $FMMemb['MemberUID']) {
      return result([], 105, '群主不能回收自己的房费');
    }
    
    $Gold = $FMMemb['Gold'];
    // 减少成员房费
    table('FamilyMember', 'rydb.websms')->where('ID', $FMMemb['ID'])->setDec('Gold', $Gold);
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'dwUserID'  => $FMMemb['MemberUID'],
      'dwCost'    => $Gold * -1,
      'dwCostType'=> 6, 
      'describe'  => sprintf('房费回收:%d 剩余房费:%d', $Gold * -1, $FMMemb['Gold'] - $Gold),
      'beleftRoomCard'=> $FMMemb['Gold'] + $Gold,
    ]);
    
    // 增加群主房费
    table('FamilyMember', 'rydb.websms')->where('ID', $FMBoss['ID'])->setInc('Gold', $Gold);
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'dwUserID'  => $FMBoss['MemberUID'],
      'dwCost'    => $Gold,
      'dwCostType'=> 6, 
      'describe'  => sprintf('房费回收:%d 剩余房费:%d', $Gold, $FMBoss['Gold'] + $Gold),
      'beleftRoomCard'=> $FMBoss['Gold'] + $Gold,
    ]);

    $eax = table('RecordRoomCard', 'rydb.record')->insert([ // 记录代充群货币明细
      'SourceUserID'=> $FMMemb['MemberUID'],
      'TargetUserID'=> $FMBoss['MemberUID'],
      'RoomCard'    => $Gold,
      'SBeforeCard' => $FMMemb['Gold'],
      'TBeforeCard' => $FMBoss['Gold'],
      'TypeID'      => 11,
      'ClientIP'    => $this->request->ip(),
      'Remarks'     => '群主回收了成员的房费',
    ]);

    return result([], 0, '回收成功');
  }
  /**
   *  @brief : xxx群下的成员钻石充值统计
   *  @return: page|JSON
   *  @detail: xxx群下的成员钻石充值统计
   */
  public function rclogAction() {
    $info = [];
    $rows = [];
    $total = 0;
    $order = [];
    $code = $this->request->param('code/d', 0); // 群号
    ////////////////////////////////////////////////////////////////////////////
    if ($code > 0) {
      $orderMap = [
        'A' => 'NickName',
        'B' => 'RoomCard',
        'C' => 'PayToday',
        'D' => 'PayALL',
      ];
      $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'C';
      $order[$orderMap[$this->orderField]] = $this->orderDirection;

      $pager = table('RYWebSMSDB.dbo.Family a', 'rydb.websms')->field([
        'b.MemberUID' => 'UserID', 'd.GameID', 'd.NickName', "ISNULL(e.HeadImgUrl, '')" => 'Avatar', 'f.RoomCard',
        '(CASE  WHEN a.AUID =b.MemberUID THEN 1 ELSE 0 END)' => 'IsBoss',
        '(SELECT ISNULL(SUM(c.RMB), 0) FROM dbo.ChargeOnline c WHERE c.UserID = b.MemberUID AND c.Status = 1 AND c.GameStatus = 1)' => 'PayToday',
        '(SELECT ISNULL(SUM(c.RMB), 0) FROM dbo.ChargeOnline c WHERE c.UserID = b.MemberUID AND c.Status = 1 AND c.GameStatus = 1 AND DATEDIFF(DAY, c.Updatetime, GETDATE()) = 0)' => 'PayALL',
      ])
      ->join('RYWebSMSDB.dbo.FamilyMember b',       'a.ID = b.FamilyID AND b.Status = 1 AND b.IsPass = 1', 'LEFT')
      ->join('RYAccountsDB.dbo.AccountsInfo d',     'd.UserID = b.MemberUID', 'LEFT')
      ->join('RYAccountsDB.dbo.IndividualDatum e',  'e.UserID = b.MemberUID', 'LEFT')
      ->join('RYTreasureDB.dbo.UserRoomCard f',     'f.UserID = b.MemberUID AND f.KindID = 0', 'LEFT')
      ->where(['a.State' => 1, 'a.Code' => $code])
      ->order($order)
      ->paginate();
      $total = $pager->total();
      $rows  = $pager->items();
      
      $info = table('RYWebSMSDB.dbo.Family a', 'rydb.websms')->field([
        'a.AUID' => 'UserID', 'a.Code', 'a.Caption', 'b.GameID', 'b.NickName', 'c.RoomCard',
      ])
      ->join('RYAccountsDB.dbo.AccountsInfo b', 'b.UserID = a.AUID', 'LEFT')
      ->join('RYTreasureDB.dbo.UserRoomCard c', 'c.UserID = a.AUID AND c.KindID = 0', 'LEFT')
      ->where(['a.State' => 1, 'a.Code' => $code])->find();
    }
    ////////////////////////////////////////////////////////////////////////////
    $retn = [
      'rows' => $rows,
      'total'=> $total,
      'page' => $this->pageCurrent,
      'size' => $this->pageSize,
      'info' => $info,
      'code' => $code,
    ];
    if ($this->request->isGet()) {
      return $this->fetch('', $retn);
    } else {
      return result($retn, 0);
    }
  }
}
